<template>
  <el-card>
    <template #header>用户管理</template>
    <template>

      <!-- 1.0 操作表单 -->
      <el-row class="setting-btn">
        <el-col > <el-button size="mini" type="primary" @click="dialogVisible = true">添加用户</el-button>  </el-col>
        <el-col > <el-button size="mini" type="danger" @click="delAll">批量删除</el-button> </el-col>
        <el-col > <el-button size="mini" type="default" @click="toggleSelection()">取消选择</el-button> </el-col>
      </el-row>

      <!-- 2.0 表格数据 -->
      <el-table ref="multipleTable" :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="realname" label="姓名"> </el-table-column>
        <el-table-column prop="username" label="账号"> </el-table-column>
        <el-table-column label="启用">
          <template v-slot="{ row }">
            <el-switch
              v-model="row.enable"
              :active-value="1"
              :inactive-value="0"
              @change="changeSate(row)"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="注册时间" width="180">
          <template v-slot="{ row }">
            {{ row.create_at | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="180">
           <template v-slot="{ row }">
            {{ row.update_at | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="210">
          <template v-slot="{ row }">
            <el-button size="mini" type="primary" @click="editUser(row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="delUser(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 3.0 分页处理 -->
       <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

      <!-- 添加用户弹窗 -->
      <el-dialog title="添加用户" :visible.sync="dialogVisible" width="35%" @close="resetForm('addUsers')">
        <el-form ref="addUsers" :model="addForm" :rules="rules" label-width="80px">
          <el-form-item label="账号名称" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="用户姓名" prop="realName">
            <el-input v-model="addForm.realName"></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="用户角色" prop="roleIds">
            <el-checkbox-group v-model="addForm.roleIds">
              <el-checkbox label="管理员"></el-checkbox>
              <el-checkbox label="普通用户"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="resetForm('addUsers')">取 消</el-button>
          <el-button size="mini" type="primary" @click="submitForm('addUsers')">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="35%" @close="resetForm('editUsers')">
        <el-form ref="editUsers" :model="editForm" :rules="rules" label-width="80px">
          <el-form-item label="账号名称" prop="username">
            <el-input v-model="editForm.username"></el-input>
          </el-form-item>
          <el-form-item label="用户姓名" prop="realname">
            <el-input v-model="editForm.realname"></el-input>
          </el-form-item>
          <el-form-item label="用户角色" prop="roleIds">
            <el-checkbox-group v-model="editForm.roleIds">
              <el-checkbox label="管理员"></el-checkbox>
              <el-checkbox label="普通用户"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="resetForm('editUsers')">取 消</el-button>
          <el-button size="mini" type="primary" @click="editConfirm('editUsers')">确认修改</el-button>
        </span>
      </el-dialog>
    </template>
  </el-card>
</template>

<script>
  import { mapActions } from 'vuex'
  import _ from 'lodash'
  import { addUser, delUser, batchUser, enableUser, disableUser, editUser }  from '@/api/user'

  export default {
    data() {
      return {
        tableData: [],
        multipleSelection: [],
        currentPage: 1,
        pageSize: 10,
        total: 0,
        dialogVisible: false,
        editDialogVisible: false,
        addForm: {
          password: '',
          realName: '',
          roleIds: [],
          username: ''
        },
        rules: {
          username: [
            { required: true, message: '请输入账号名称', trigger: 'blur' },
            { min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur' }
          ],
          realName: [
            { required: true, message: '请输入用户姓名', trigger: 'blur' },
            { min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入用户密码', trigger: 'blur' },
            { min: 6, max: 13, message: '长度在 6 到 12 个字符', trigger: 'blur' }
          ],
          roleIds: [
            { required: true, message: '请选择用户角色', trigger: 'blur' }
          ]
        },
        editForm: {
          realName: '',
          roleIds: [],
          username: ''
        }
      }
    },
    created() {
      this.getUsers()
    },
    methods: {
      ...mapActions('user', ['getUserList']),
      async getUsers() {
        const { data, count } = await this.getUserList({
          page: this.currentPage,
          limit: this.pageSize
        })
        console.log(data)
        this.tableData = data
        this.total = count
      },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row)
          });
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.getUsers()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.getUsers()
      },
      // 重置表单
      resetForm(formName) {
        this.dialogVisible = false
        this.editDialogVisible = false
        this.addForm.roleIds = ''
        this.editForm.roleIds = ''
        this.$refs[formName].resetFields()
      },
      // 添加用户
      submitForm(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            const addObj = _.cloneDeep(this.addForm)
            addObj.roleIds = addObj.roleIds.length + ''
            if((addObj.roleIds - 0) >= 1) {
              addObj.roleIds = '1,2'
            }
            const {success, msg} = await addUser(addObj)
            if(success) {
              this.$message.success(msg)
              this.getUsers()
              this.dialogVisible = false
            } else {
              this.$message.error(msg)
            }
          } else {
            return false
          }
        });
      },
      // 删除用户
      delUser(id) {
        this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {success, msg} = await delUser(id)
            if(success) {
              this.$message.success(msg)
              this.getUsers()
              this.dialogVisible = false
            } else {
              this.$message.error(msg)
            }
        }).catch(() => {
          this.$message({ type: 'info', message: '已取消删除'})
        })
      },
      // 批量删除
      delAll() {
        if(this.multipleSelection.length <= 0) return
        this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const ids = this.multipleSelection.map(item => item.id)
          const {success, msg} = await batchUser({ ids })
            if(success) {
              this.$message.success(msg)
              this.getUsers()
              this.dialogVisible = false
            } else {
              this.$message.error(msg)
            }
        }).catch(() => {
          this.$message({ type: 'info', message: '已取消删除'})
        })
      },
      // 改变状态
      async changeSate(row) {
        if(row.enable) {
          const {success, msg} = await enableUser({ userId: row.id })
            if(success) {
              this.$message.success(msg)
            } else {
              this.$message.error(msg)
            }
        }else {
          const {success, msg} = await disableUser({ userId: row.id })
            if(success) {
              this.$message.success(msg)
            } else {
              this.$message.error(msg)
            }
        }
      },
      // 编辑用户
      editUser(row) {
        this.editForm = { ...row }
        this.$set(this.editForm, 'roleIds', [])
        console.log(row);
        row.roles.forEach(item => {
          this.editForm.roleIds.push(item.name)
        })
        this.editDialogVisible = true
      },
      // 确认修改
      editConfirm(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            const addObj = {
              userId: this.editForm.id,
              realName: this.editForm.realname,
              username: this.editForm.username
            }
            addObj.roleIds = this.editForm.roleIds.length + ''
            if((addObj.roleIds - 0) >= 1) {
              addObj.roleIds = '1,2'
            }
            const {success, msg} = await editUser(addObj)
            if(success) {
              this.$message.success(msg)
              this.getUsers()
              this.editDialogVisible = false
            } else {
              this.$message.error(msg)
            }
          } else {
            return false
          }
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
.setting-btn {
  display: flex;
  .el-col {
    width: 100px;
  }
}

.el-table {
  margin: 24px 0;
}

.el-dialog {
  .el-select {
    width: 100%;
  }
}
</style>